接續昨天在 index.js
寫完 reducer 的程式碼,現在要把這些程式碼分別放進各自的 reducer 裡,實現最結構化的撰寫模式。我們在 reducer
資料夾裡,新增 characters_reducer.js
和 heros_reducer.js
在 characters_reducer
複製貼上最簡單!但記得要在最後一行 export export default characters;
import characters_json from '../data/characters.json';
import { ADD_CHARACTER } from '../actions';
function characters(state = characters_json, action){
switch(action.type){
case ADD_CHARACTER:
let characters = state.filter(item => item.id !== action.id );
return characters;
default:
return state;
}
}
export default characters;
同樣地,舉一反三,在 heros_reducer
也是做一樣的動作~
import { ADD_CHARACTER } from '../actions';
import characters_json from '../data/characters.json';
function heros(state = [], action){
switch(action.type) {
case ADD_CHARACTER:
let heros = [...state, createCharacter(action.id)];
return heros;
default:
return state;
}
}
function createCharacter(id) {
let character = characters_json.find(c => c.id === id);
return character;
}
export default heros;
現在 index.js
的樣貌~程式碼乾淨許多!
import { combineReducers } from 'redux';
function createCharacter(id) {
let character = characters_json.find(c => c.id === id);
return character;
}
const rootReducer = combineReducers({
characters,
heros
})
export default rootReducer;
但是別忘了,剛剛移到 reducer 裡的 characters 和 hero 要 import 回來
import characters from './characters_reducer.js';
import heros from './heros_reducer.js';
並把 createCharacter
function 放到 helper.js
裡
import characters_json from '../data/characters.json';
export function createCharacter(id) {
let character = characters_json.find(c => c.id === id);
return character;
}
因為 heros reducer
和 createCharacter
作用有關聯性,因此我們要在 heros_reducer.js
import createCharacter
import { createCharacter } from './helper';